<!DOCTYPE html>
<html>
<head>
	<title>拖曳</title>
	<meta charset='utf-8' />
	<meta name='viewport' content='width=device-width,initial-scale=1' />
	<style type="text/css">
		#slider-box {
			position: relative;
			margin: 100px;
			width: 200px;
			height: 30px;
			border: 1px solid #ddd;
		}
		#slider {
			position: absolute;
			top: 0;
			left: 0px;
			width: 30px;
			height: 100%;
			background: #aaa;
		}
		.success {
			display: inline-block;
			width: 0px;
			height: 100%;
			background-color: green;
		}
		.gray {
			float: right;
			width: 100%;
			height: 100%;
			background-color: #ddd;
		}
	</style>
</head>
<body>
	<section id='slider-box'>
		<span class='success'></span>
		<div id='slider'></div>
		<span class='gray'></span>
	</section>
<script type="text/javascript">
	'use strict'
	window.onload = function(){
		var slider = document.getElementById('slider'),
			box = document.getElementById('slider-box');
		function Drag(obj){
			this.parameter = {
				left: 0,
				top: 0,
				currentX: 0,
				currentY: 0,
				flag: false
			}
			this.target = obj;
			this.startDrag().mouseDown().mouseUp().mouseMove();
		}
		Drag.prototype = {
			getCss: function(obj,name){
				return obj.currentSyle ? obj.currentSyle[name] : document.defaultView.getComputedStyle(obj,false)[name];
			},
			startDrag: function(){
				if(this.getCss(this.target,'left') != 'auto'){
					this.parameter.left = this.getCss(this.target,'left');
				}
				if(this.getCss(this.target,'top') != 'auto'){
					this.parameter.top = this.getCss(this.target,'top');
				}
				return this;
			},
			mouseDown: function(){
				var _this = this;
				this.target.addEventListener('mousedown',function(e){
					_this.parameter.flag = true;
					var event = e ? e : window.event;
					_this.parameter.currentX = event.clientX;
					_this.parameter.currentY = event.clientY;
				})
				return this;
			},
			mouseUp: function(){
				var _this = this;
				document.addEventListener('mouseup',function(e){
					_this.parameter.flag = false;
					if(_this.getCss(_this.target,'left') != 'auto'){
						_this.parameter.left = _this.getCss(_this.target,'left');
					}
					if(_this.getCss(_this.target,'top') != 'auto'){
						_this.parameter.top = _this.getCss(_this.target,'top');
					}
				})
				return this;
			},
			mouseMove: function(){
				var _this = this;
				document.addEventListener('mousemove',function(e){
					var event = e ? e : window.event;
					if(_this.parameter.flag){
						var nowX = e.clientX,
							nowY = e.clientY,
							distance = {};
						distance.left = nowX - _this.parameter.currentX;
						distance.top = nowY - _this.parameter.currentY;
						_this.target.style.left = parseInt(_this.parameter.left) + distance.left +　'px';
						_this.target.style.top = parseInt(_this.parameter.top) + distance.top + 'px';
					}
				})
				return this;
			}
		}
		new Drag(slider);
	}
</script>
</body>
</html>